package com.adonis.ejoy.adapter;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adonis.ejoy.CommentActivity;
import com.adonis.ejoy.Item.Post;
import com.adonis.ejoy.R;
import com.adonis.ejoy.utils.CircleTransformation;
import com.adonis.ejoy.utils.HttpUtil;
import com.jude.rollviewpager.RollPagerView;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
    private String baseURL;
    private int login_uid;
    private List<Post> mPostList;
    private int uid;
    private int pid;
    private Activity activity;
    int avatarSize=0;           //动态发布者头像的大小

    ImageButton btn_Like;        //点赞图片的实例
    Boolean[][] isLiked;           //判断是否点赞和收藏

    TextView position_text;     //当前动态在recycleView中的位置
    TextView likeCounts;

    View view=null;
    ViewHolder holder;

    static class ViewHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.img_own)
        ImageView ownImage;
        @BindView(R.id.name_own)
        TextView ownName;
        @BindView(R.id.ivPostCenter)
        RollPagerView postCenterView;
        @BindView(R.id.item_position)
        TextView item_position;
        @BindView(R.id.btn_Like)
        ImageButton imgbtn_Like;
        @BindView(R.id.btn_collect)
        ImageButton btn_collect;
        @BindView(R.id.like_counts)
        TextView like_counts;
        @BindView(R.id.name_author)
        TextView authorName;
        @BindView(R.id.text_author)
        TextView authorText;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }

    public PostAdapter(List<Post> postList, Activity activity) {
        this.mPostList = postList;
        isLiked = new Boolean[mPostList.size()][2];
        this.activity = activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item,parent,false);
        ButterKnife.bind(this,view);
        baseURL = parent.getContext().getString(R.string.baseURL);
        uid = ((TextView)activity.findViewById(R.id.user_info)).getMaxWidth();
        holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        login_uid = ((TextView)activity.findViewById(R.id.user_info)).getMaxWidth();
        Post post=mPostList.get(position);
        avatarSize = holder.itemView.getResources().getDimensionPixelSize(R.dimen.global_menu_avatar_size);
        Picasso.with(holder.itemView.getContext())                     //指定图片的父布局
                .load("http://img2.imgtn.bdimg.com/it/u=408831202,2051725336&fm=26&gp=0.jpg") //post.getImg();
                .placeholder(R.drawable.img_circle_placeholder)      //在网络请求还没有完成时显示的图片，它必须是本地图片
                .resize(avatarSize, avatarSize)                      //设置图片大小
                .centerCrop()                                           //居中裁剪
                .transform(new CircleTransformation())                 //将图片以圆形方式显示
                .into(holder.ownImage);
        holder.ownName.setText(post.getName());
        PictureLoopAdapter pictureLoopAdapter = new PictureLoopAdapter(holder.postCenterView);
        String[] list_img = initImags(post.getPhoto());
        pictureLoopAdapter.setPictures(list_img);
        holder.postCenterView.setAdapter(pictureLoopAdapter);
        holder.like_counts.setText(post.getLikes().toString() + " likes");
        holder.item_position.setWidth(position);          //保存这条动态在recycleView中的索引
        holder.item_position.setMaxWidth(Integer.parseInt(post.getUID().toString()));    //保存发布这条动态的用户的uid
        holder.item_position.setMaxHeight(Integer.parseInt(post.getPID().toString()));    //保存这条动态的pid
        if(!"".equals(post.getText())){
            holder.authorName.setText(post.getName());
            holder.authorText.setText( ": " + post.getText());
        }
        isLiked[position][0] = post.getIsLikeflag();                           //第0列表示是否点赞
        if(post.getIsLikeflag()){
            holder.imgbtn_Like.setImageResource(R.drawable.ic_heart_red);
        }
        isLiked[position][1] = post.getIsFollowflag();                           //第1列表示是否关注
        if(post.getIsFollowflag()){
            holder.btn_collect.setImageResource(R.drawable.collect_yes);
        }
    }

    private String[] initImags(String path) {
        String imgPath = path.substring(path.indexOf("[")+1,path.lastIndexOf("]"));
//        Log.d("imgPath",  imgPath);
        return imgPath.split(",");
    }

    @Override
    public int getItemCount() { return mPostList.size();}

    @OnClick({R.id.post_own,R.id.btn_collect,R.id.btn_Like,R.id.btn_Comments})
    public void onClick(View v){
        LinearLayout v_parent = ((LinearLayout)v.getParent().getParent());
        int position = 0;
        if(v.getId() != R.id.btn_collect){
            position_text = v_parent.findViewById(R.id.item_position);   //v.getParent()获取v的父控件
            position = position_text.getWidth();
            uid = position_text.getMaxWidth();              //获取当发布这条动态的用户的uid
            pid = position_text.getMaxHeight();             //获取当前动态的PID
            //Log.d("v.getparent()", v.getParent().getParent().toString());
        }
        switch (v.getId()){
            case R.id.post_own:
                Toast.makeText(v.getContext(), "open user profile", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_collect:
                v_parent = (LinearLayout) v_parent.getParent();
                position_text = v_parent.findViewById(R.id.item_position);   //v.getParent()获取v的父控件
                position = position_text.getWidth();
                uid = position_text.getMaxWidth();              //获取发布这条动态的用户的uid
                if(!isLiked[position][1]){
                    ((ImageButton)v).setImageResource(R.drawable.collect_yes);
                    Toast.makeText(v.getContext(), "you collected it", Toast.LENGTH_SHORT).show();
                    isLiked[position][1]=true;
                }else {
                    ((ImageButton)v).setImageResource(R.drawable.collect_no);
                    Toast.makeText(v.getContext(), "you canceled this operation", Toast.LENGTH_SHORT).show();
                    isLiked[position][1]=false;
                }
                updateFollows(isLiked[position][1]);
                break;
            case R.id.btn_Like:
                btn_Like=(ImageButton) v;
                likeCounts = v_parent.findViewById(R.id.like_counts);
                animateHeartButton(position);
                break;
            case R.id.btn_Comments:
                Intent intent = new Intent(v.getContext(), CommentActivity.class);
                intent.putExtra("uid",login_uid);
                intent.putExtra("pid",pid);
                v.getContext().startActivity(intent);
              //  finalize();
                Toast.makeText(v.getContext(), "please comment", Toast.LENGTH_SHORT).show();
                break;
        }

    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.obj instanceof Boolean){
                updateLike((Boolean)msg.obj);
            }
        }
    };
    private void updateLike(Boolean flag) {

        String url = baseURL + "mvc/praise";
        RequestBody body = new FormBody.Builder()
                .add("uid", login_uid + "")
                .add("pid", pid + "")
                .add("flag",flag.toString())
                .build();
        HttpUtil.sendPostRequest(url, body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Toast.makeText(view.getContext(), "操作失败", Toast.LENGTH_SHORT).show();
                Log.d("点赞", "操作失败");
            }

            @Override
            public void onResponse(Call call, Response response){
                //Toast.makeText(view.getContext(), "操作成功", Toast.LENGTH_SHORT).show();
                Log.d("点赞", "操作成功");
            }
        });
    }

    private void updateFollows(Boolean flag) {
        String url = baseURL + "mvc/follow";
        RequestBody body = new FormBody.Builder()
                .add("uid", login_uid + "")
                .add("pid", uid+ "")
                .add("flag",flag.toString())
                .build();
        HttpUtil.sendPostRequest(url, body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Toast.makeText(view.getContext(), "操作失败", Toast.LENGTH_SHORT).show();
                Log.d("关注", "操作失败");
            }

            @Override
            public void onResponse(Call call, Response response){
                //Toast.makeText(view.getContext(), "操作成功", Toast.LENGTH_SHORT).show();
                Log.d("关注", "操作成功");
            }
        });
    }

    private void animateHeartButton(final int position) {
        final AccelerateInterpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator();           //加速器，速度越来越快
        final OvershootInterpolator OVERSHOOT_INTERPOLATOR = new OvershootInterpolator(4);    //快速到达终点超出一小步然后回到终点
        AnimatorSet animatorSet = new AnimatorSet();

        ObjectAnimator rotationAnim = ObjectAnimator.ofFloat(btn_Like, "rotation", 0f, 360f);
        rotationAnim.setDuration(300);
        rotationAnim.setInterpolator(ACCELERATE_INTERPOLATOR);

        ObjectAnimator bounceAnimX = ObjectAnimator.ofFloat(btn_Like, "scaleX", 0.2f, 1f);
        bounceAnimX.setDuration(300);
        bounceAnimX.setInterpolator(OVERSHOOT_INTERPOLATOR);

        ObjectAnimator bounceAnimY = ObjectAnimator.ofFloat(btn_Like, "scaleY", 0.2f, 1f);
        bounceAnimY.setDuration(300);
        bounceAnimY.setInterpolator(OVERSHOOT_INTERPOLATOR);
        bounceAnimY.addListener(new AnimatorListenerAdapter() {
            int currentLikeCounts=Integer.parseInt(likeCounts.getText().toString().split(" ")[0]);
            int newLikeCounts;
            @Override
            public void onAnimationStart(Animator animation) {
                if(isLiked[position][0] == null || !isLiked[position][0]){
                    btn_Like.setImageResource(R.drawable.ic_heart_red);
                    Toast.makeText(view.getContext(), "liked", Toast.LENGTH_SHORT).show();
                    newLikeCounts=currentLikeCounts+1;
                    /*String likesCountTextFrom = ts.getResources().getQuantityString(
                            R.plurals.likes_count, currentLikeCounts - 1, currentLikeCounts - 1
                    );
                    ts.setCurrentText(likesCountTextFrom);*/
                    isLiked[position][0]=true;
                }else {
                    btn_Like.setImageResource(R.drawable.heart_32px);
                    Toast.makeText(view.getContext(), "unliked", Toast.LENGTH_SHORT).show();
                    newLikeCounts=currentLikeCounts-1;
                    isLiked[position][0]=false;
                }
                String text_like = new Integer(newLikeCounts).toString();
                String next = newLikeCounts>1 ? " likes":" like";
                likeCounts.setText(text_like + next);

                Message message = new Message();
                message.obj = isLiked[position][0];
                handler.sendMessage(message);
            }
        });
        animatorSet.play(bounceAnimX).with(bounceAnimY).after(rotationAnim);
        animatorSet.start();
    }
}
